import * as React from "react";
import { Row, Col, Modal, Spin } from "antd";
import moment from "moment";
import ReactEcharts from "echarts-for-react";
import DepartmentMessage from "./compontents/DepartmentMessage";
import Condition from "./compontents/Condition";
import ConditionTable from "./compontents/ConditionTable";
import { statistical, statisticalExportExcel } from "../ServeApi";
import { AjaxData } from "../../../../data/interface/publicInterface";

export interface SubItemEnergyStatisticsProps {}

export interface SubItemEnergyStatisticsState {}

class SubItemEnergyStatistics extends React.Component<
  SubItemEnergyStatisticsProps,
  SubItemEnergyStatisticsState
> {
  public checkedKeys: string[] = [];
  private energyType: number = 1;
  private option: any = {};
  private dataSouce: any = null;
  private columns: any[] = [
    {
      title: "名称",
      width: 100,
      dataIndex: "name",
      key: "name",
      fixed: "left",
    },
  ];
  state = { loading: false };
  render() {
    return (
      <div className="SubItemEnergyStatistics">
        <Row>
          <Col span={24} style={{ paddingBottom: 12 }}>
            <Condition
              onSubmit={(data: any) => {
                this.getCondition(data);
              }}
              onDownLoad={(data: any) => {
                this.downLoad(data);
              }}
            />
          </Col>
          <Col span={6} style={{ paddingRight: 12 }}>
            <DepartmentMessage
              onSelect={(sele: string[]) => {
                this.selectDepartments(sele);
              }}
            />
          </Col>
          <Col span={18}>
            <Row>
              <Col span={24}>
                <Spin spinning={this.state.loading}>
                  <ConditionTable
                    columns={this.columns}
                    dataSouce={this.dataSouce}
                  />
                </Spin>
              </Col>
              <Col span={24} style={{ paddingTop: 16 }}>
                <div className="rowcon_body">
                  <Spin spinning={this.state.loading}>
                    <ReactEcharts
                      option={this.option}
                      notMerge={true}
                      lazyUpdate={true}
                      style={{ height: 350 }}
                      // theme="dark"
                    />
                  </Spin>
                </div>
              </Col>
            </Row>
          </Col>
        </Row>
      </div>
    );
  }
  //获取选中的分项回调
  selectDepartments(sele: string[]) {
    this.checkedKeys = sele;
    this.forceUpdate();
  }
  //下载回调
  downLoad(data: any) {
    let pream = {
      energyType: data.type,
      idList: this.checkedKeys,
      time: moment(data.dateString).valueOf(),
      timeType: data.date,
    };
    this.DownLoad(pream);
  }
  //获取筛选条件
  getCondition(data: any) {
    this.energyType = data.type;
    this.updateDataSouce(data);
    this.forceUpdate();
  }
  //更新数据
  updateDataSouce(data: any) {
    let pream = {
      energyType: data.type,
      idList: this.checkedKeys,
      time: moment(data.dateString).valueOf(),
      timeType: data.date,
    };
    this.statistical(pream);
  }
  //生成echarts对象
  getWarnOption(data: any) {
    if (data) {
      let { columnNames, datas } = data;
      let str = this.energyType === 1 ? "kW·h" : "t";
      let nameTextArr: string[] = [];
      let seriesData = datas.map((Item) => {
        nameTextArr.push(Item.name);
        return {
          name: Item.name,
          type: "line",
          stack: "总量",
          data: Item.data,
        };
      });
      return {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: nameTextArr,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: columnNames,
        },
        yAxis: {
          name: "单位：" + str,
          type: "value",
        },
        series: seriesData,
      };
    } else {
      return {};
    }
  }
  //格式化表格头部，数据
  formattingDataSouce(data: any) {
    if (data) {
      //制造表头
      let columns: any[] = [
        {
          title: "名称",
          width: 100,
          dataIndex: "name",
          key: "name",
          fixed: "left",
        },
      ];
      let columnNames: string[] = data.columnNames;
      columnNames.map((item: string, index: number) => {
        let iOva = {
          title: item,
          dataIndex: "Column" + index,
          key: "Column" + index,
          width: 150,
        };
        columns.push(iOva);
        return iOva;
      });
      let datas: any[] = data.datas;
      //制造数据
      let dataSouce: any[] = datas.map((list) => {
        let arrData = list.data;
        let obj = {};
        arrData.map((item: any, index: number) => {
          obj["Column" + index] = item;
          return item;
        });
        let newObj = {};
        Object.assign(newObj, obj, list);
        return newObj;
      });
      this.columns = columns;
      this.dataSouce = dataSouce;
      this.forceUpdate();
    } else {
      this.columns = [];
      this.dataSouce = [];
      this.forceUpdate();
    }
  }
  setFileName(timeType: number, time: number, str: string) {
    let fileName: string = "";
    switch (timeType) {
      case 2:
        fileName += moment(time).format("YYYY-MM-DD") + "日";
        break;
      case 3:
        fileName += moment(time).format("YYYY-MM") + "月";
        break;
      case 4:
        fileName += moment(time).format("YYYY") + "年";
        break;

      default:
        break;
    }

    fileName += str;
    return fileName;
  }
  /**数据请求 */
  //分项用能统计下载
  DownLoad(pream: any) {
    let fileName: string = this.setFileName(
      pream.timeType,
      pream.time,
      "分项用能统计.xlsx"
    );
    statisticalExportExcel(JSON.stringify(pream))
      .then((res) => {
        return res;
      })
      .then((blob) => {
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        // 释放的 URL 对象以及移除 a 标签
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      });
  }
  //分项用能统计
  async statistical(pream: any) {
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await statistical(JSON.stringify(pream)).catch((err) => {
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.formattingDataSouce(json.data);
        _this.option = _this.getWarnOption(json.data);
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}

export default SubItemEnergyStatistics;
